package com.lmf.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lmf.cloud.em.ReturnCodeEnum;
import com.lmf.cloud.entity.TAccount;
import com.lmf.cloud.mapper.TAccountMapper;
import com.lmf.cloud.resp.ResultData;
import com.lmf.cloud.service.TAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiuMingFu
 * @since 2024-08-01
 */
@Service
public class TAccountServiceImpl extends ServiceImpl<TAccountMapper, TAccount> implements TAccountService {
    
    @Resource
    private TAccountMapper tAccountMapper;
    
    /**
     * 扣减账户余额
     *
     * @param userId 用户id
     * @param count  金额
     * @return
     * @author LiuMingFu
     * @date 2024/8/1
     */
    @Override
    public ResultData<Boolean> decreaseAccount(Long userId, Integer count) {
        if (userId == null || count == null) {
            return ResultData.fail(ReturnCodeEnum.RC402);
        }
        LambdaUpdateWrapper<TAccount> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(TAccount::getUserId, userId);
        wrapper.setSql("residue = residue - " + count);
        wrapper.setSql("used = used + " + count);

        boolean update = this.update(wrapper);
        if (update) {
            return ResultData.success(true);
        }
        return ResultData.fail(ReturnCodeEnum.BUSINESS_ERROR);
    }
}
